package com.ufida.ids.service.impl;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hereway.core.context.PageBean;
import com.hereway.core.dao.IBaseDAO;
import com.hereway.core.exception.ServiceException;
import com.hereway.core.service.BaseServiceImpl;
import com.ufida.ids.dao.IOrgDAO;
import com.ufida.ids.model.OrgModel;
import com.ufida.ids.service.IOrgService;
import com.ufida.ids.util.DateUtil;
import com.ufida.ids.util.ExtUtil;
import com.ufida.ids.util.StringUtil;

@Service("orgService")
public class OrgServiceImpl extends BaseServiceImpl<OrgModel,Long> implements IOrgService {
	@Autowired
	IOrgDAO orgDAO;
	
	@Override
	protected IBaseDAO<OrgModel, Long> getDAO() {
		return orgDAO;
	}
	
	@Override
	public List<OrgModel> findByParentId(Long parentId) throws ServiceException {
		return orgDAO.findByParentId(parentId);
	}
	
	public String getOrgListStr(List<OrgModel> l) throws ServiceException{
		JSONArray json = new JSONArray();
		for(OrgModel org:l){
			List tempL = findByParentId(org.getOrgId());
			JSONObject ob = new JSONObject();
			ob.put("id", org.getOrgId());
			ob.put("text", org.getOrgName());
			ob.put("cls", "folder");
			ob.put("deptcode", org.getOrgCode());
//			if(tempL.size() == 0){
//				ob.put("leaf", true);
//			}
			json.add(ob);
		}
		return json.toString();
	}
	
	public String getOrgListByConPagging(String currentOrgId, String orgName, int pageNum) throws ServiceException{
		PageBean page = new PageBean();
		page.setIndex(pageNum);
		String whereStr = getConStr(currentOrgId, orgName);
		List<OrgModel> l = orgDAO.find(whereStr, page);
		for(OrgModel org: l){
			org.setCreateTsStr(DateUtil.getDateStrPattern1(org.getCreateTs()));
		}
		int count = orgDAO.findCountByCon(whereStr);
		String retStr = ExtUtil.getJosonStr(l,new String[]{"postModels"},count);
		//格式化日期
		return retStr;
	}

	
	public List find(String idStr)throws ServiceException{
		String whereStr = " where orgId in"+ idStr;
		return orgDAO.find(whereStr);
	}

	
	private static String getConStr(String currentOrgId, String orgName){
		StringBuffer whereStr = new StringBuffer("where 1=1 "); 
		if(!"".equals(currentOrgId)){
			whereStr.append(" and parentOrgId = ").append(currentOrgId);
		}
		
		if(!"".equals(orgName)){
			whereStr.append(" and (orgCode like '%" + orgName + "%' or orgName like '%"+orgName+"%')");
		}
		
		return whereStr.toString();
	}
	
}
